package edu.fight.shiro.config;

import edu.fight.constant.Constant;
import edu.fight.shiro.cache.RedisCacheManager;
import edu.fight.shiro.realm.MyRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //1.realm
    @Bean
    public MyRealm myRealm(){
        MyRealm realm = new MyRealm();

        realm.setCacheManager(new RedisCacheManager());
        // 开启全局缓存
        realm.setCachingEnabled(true);
        realm.setAuthenticationCachingEnabled(true);
        realm.setAuthenticationCacheName(Constant.CACHE_NAME_AUTHENTICATION.getCacheCode());
        realm.setAuthorizationCachingEnabled(true);
        realm.setAuthorizationCacheName(Constant.CACHE_NAME_AUTHORIZATION.getCacheCode());


        return realm;
    }

    //2.SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);

        return  securityManager;
    }
    //3.filterFactory
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

//        shiroFilterFactoryBean.setLoginUrl("/err/login");
//        shiroFilterFactoryBean.setUnauthorizedUrl("/err/auth");

        Map<String,String> filterMap  = new LinkedHashMap<>();
        filterMap.put("/err/**","anon"); //公共错误url：允许匿名访问
        filterMap.put("/auth/**","anon"); //允许匿名访问
        filterMap.put("/**","authc");//其他资源需要授权
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return shiroFilterFactoryBean;

    }


    //4.开启shiro注解支持
//    @Bean
//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
//        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor =
//                new AuthorizationAttributeSourceAdvisor();
//        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
//        return authorizationAttributeSourceAdvisor;
//    }
}
